package com.toidep.fragment.others;

import java.util.ArrayList;

import org.json.JSONException;
import org.json.JSONObject;

import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnFocusChangeListener;
import android.view.View.OnKeyListener;
import android.view.View.OnTouchListener;
import android.view.ViewGroup;
import android.view.inputmethod.EditorInfo;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ImageView.ScaleType;
import android.widget.TextView.OnEditorActionListener;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.toidep.R;
import com.toidep.activities.MainActivity;
import com.toidep.adapters.AlbumSuggestionAdapter;
import com.toidep.adapters.CommentAdapter;
import com.toidep.api.ApiController;
import com.toidep.api.ParseJSON;
import com.toidep.base.BaseFragment;
import com.toidep.config.ConfigUtility;
import com.toidep.config.Constants;
import com.toidep.entities.AlbumEntity;
import com.toidep.entities.GalleryEntity;
import com.toidep.entities.TagEntity;
import com.toidep.imageviewer.ImageViewerActivity;
import com.toidep.interfaces.DialogListener;
import com.toidep.interfaces.ResponseListener;
import com.toidep.payment.PaymentControl;
import com.toidep.preference.SharePreference;
import com.toidep.utilities.DialogUtility;
import com.toidep.widgets.sectionlist.AmazingListView;

public class AlbumDetailFragment extends BaseFragment implements OnClickListener {

	private MainActivity mainActivity;
	
	private View view;

	private ImageView imgMainItem;
	private LinearLayout layoutListItem;
	
	private ImageView imvModelImage;
	private TextView txvModelName;
	private TextView txvAlbumTitle, txvAlbumUpdateTime, txvTotalView, txvIntroduction;
	private LinearLayout layoutTags;
	private TextView buttonComment;
	private EditText edtComment;
	
	private RelativeLayout layoutButtonIntroduction, layoutButtonSuggestion, layoutButtonComment;
	private RelativeLayout layoutIntroduction, layoutSuggestion, layoutComment;
	
	private AmazingListView amazingListViewAlbumSuggestion, amazingListViewAlbumComments;
	private AlbumSuggestionAdapter albumAdapter;
	private CommentAdapter commentAdapter;
	
	private boolean isRequestIntroductionData = false;
	private boolean isRequestSuggestionData = false;
	private boolean isRequestCommentData = false;
	
	private String album_id = "";
	private String album_view = "";
	private String imageUrl = "";
	
//	private ImageFetcher imageFetcher;
	private int widthImage, heightImage;
	private int widthImageView, heightImageView;
	
	public void setValues(String album_id) {
		this.album_id = album_id;
	}
	
	/**
	 * Set lai cac base value cho fragment: cac item cua thanh header, currentCategory cua menuSideBar
	 */
	public void setBaseValues() {
		mainActivity.currentCategory = Constants.CATEGORY_ALBUM_DETAIL;
		mainActivity.mainFragment.setTittle(mainActivity.getString(R.string.label_category_album));
		mainActivity.mainFragment.showButtonSlide(false);
		
		isRequestIntroductionData = false;
		isRequestSuggestionData = false;
		isRequestCommentData = false;
	}
	
	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {

		view = inflater.inflate(R.layout.fragment_album_detail, container, false);

		mainActivity = (MainActivity) getActivity();
		
		initComponents();
		
		setBaseValues();
		
		switchTab(Constants.TAB_MODE_ALBUM_INTRODUCTION);
		
		return view;
	}

	@Override
	public void onResume() {
		// TODO Auto-generated method stub
		super.onResume();
		boolean loginStatus = SharePreference.getInstance(mainActivity)
				.getLoginStatus();
		if (loginStatus) {
			edtComment.setText("");
			
		} else {
			edtComment.setText("Đề nghị login để bình luận");
		}
	}
	private void initComponents() {

		imgMainItem = (ImageView) view.findViewById(R.id.imgMainItem);
		layoutListItem = (LinearLayout) view.findViewById(R.id.layoutListItem);;
		
		imvModelImage = (ImageView) view.findViewById(R.id.imgModelThumb);
		txvModelName = (TextView) view.findViewById(R.id.txvModelName);
		txvAlbumTitle = (TextView) view.findViewById(R.id.txvAlbumTitle);
		txvAlbumUpdateTime = (TextView) view.findViewById(R.id.txvAlbumUpdateTime);
		txvTotalView = (TextView) view.findViewById(R.id.txvTotalViews);
		txvIntroduction = (TextView) view.findViewById(R.id.txvIntroduction);
		
		buttonComment = (TextView) view.findViewById(R.id.buttonComment);
		buttonComment.setOnClickListener(this);
		edtComment = (EditText) view.findViewById(R.id.edtComment);
		
		layoutTags = (LinearLayout) view.findViewById(R.id.layoutTags);
		
		layoutButtonIntroduction = (RelativeLayout) view.findViewById(R.id.layoutButtonIntroduction);
		layoutButtonIntroduction.setOnClickListener(this);
		layoutButtonSuggestion = (RelativeLayout) view.findViewById(R.id.layoutButtonSuggestion);
		layoutButtonSuggestion.setOnClickListener(this);
		layoutButtonComment = (RelativeLayout) view.findViewById(R.id.layoutButtonComment);
		layoutButtonComment.setOnClickListener(this);

		layoutIntroduction = (RelativeLayout) view.findViewById(R.id.layoutIntroduction);
		layoutSuggestion = (RelativeLayout) view.findViewById(R.id.layoutSuggestion);
		layoutComment = (RelativeLayout) view.findViewById(R.id.layoutComment);
		
		amazingListViewAlbumSuggestion = (AmazingListView) view.findViewById(R.id.amazingListViewSuggestion);
		amazingListViewAlbumComments = (AmazingListView) view.findViewById(R.id.amazingListViewComment);
		
		//Bug #220 - Start
		edtComment.setOnTouchListener(new OnTouchListener() {
			
			@Override
			public boolean onTouch(View v, MotionEvent event) {
				if(event.getAction() == MotionEvent.ACTION_DOWN){
					if(!mainActivity.checkUserLogon()){
						return true;
					}
				}
				return false;
			}
		});
		//Bug #220 - End
		// Bug #314 - Start
		/*edtComment.setOnKeyListener(new OnKeyListener() {
			
			@Override
			public boolean onKey(View v, int keyCode, KeyEvent event) {
				// TODO Auto-generated method stub
				if (keyCode == KeyEvent.KEYCODE_ENTER && event.getAction() == KeyEvent.ACTION_UP) {
					postComment();
					
					return true;
				}
				return false;
			}
		});*/
		edtComment.setImeOptions(EditorInfo.IME_ACTION_DONE);
		edtComment.setOnEditorActionListener(new OnEditorActionListener() {
			
			@Override
			public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
					postComment();
				return true;
			}
		});
		// Bug #314 - End
	}
	
	private void switchTab(int tabMode) {
		switch (tabMode) {
		case Constants.TAB_MODE_ALBUM_INTRODUCTION:
			// Menu color
			layoutButtonIntroduction.setBackgroundResource(R.drawable.bg_red_normal);
			layoutButtonSuggestion.setBackgroundResource(R.drawable.bg_button_menu_trasparent);
			layoutButtonComment.setBackgroundResource(R.drawable.bg_button_menu_trasparent);
			
			// Layout content
			layoutIntroduction.setVisibility(View.VISIBLE);
			layoutSuggestion.setVisibility(View.GONE);
			layoutComment.setVisibility(View.GONE);

			// Request data
			requestIntroductData();
			break;
		case Constants.TAB_MODE_ALBUM_SUGGESTION:
			// Menu color
			layoutButtonSuggestion.setBackgroundResource(R.drawable.bg_red_normal);
			layoutButtonIntroduction.setBackgroundResource(R.drawable.bg_button_menu_trasparent);
			layoutButtonComment.setBackgroundResource(R.drawable.bg_button_menu_trasparent);
			
			// Layout content
			layoutSuggestion.setVisibility(View.VISIBLE);
			layoutIntroduction.setVisibility(View.GONE);
			layoutComment.setVisibility(View.GONE);

			// Request data
			requestSuggestionData();
			break;
		case Constants.TAB_MODE_ALBUM_COMMENT:
			// Menu color
			layoutButtonComment.setBackgroundResource(R.drawable.bg_red_normal);
			layoutButtonIntroduction.setBackgroundResource(R.drawable.bg_button_menu_trasparent);
			layoutButtonSuggestion.setBackgroundResource(R.drawable.bg_button_menu_trasparent);
			
			// Layout content
			layoutComment.setVisibility(View.VISIBLE);
			layoutIntroduction.setVisibility(View.GONE);
			layoutSuggestion.setVisibility(View.GONE);

			// Request data
			requestCommentData();
			break;
		}
	}
	
	/**
	 * request API Detail Album
	 */
	private void requestIntroductData() {
		if (isRequestIntroductionData)
			return;
		
		isRequestIntroductionData = true;
		// Lay thong tin chi tiet cua Album
		ApiController.getAlbumDetail(mainActivity, album_id, new ResponseListener() {
			@Override
			public void processResponse(int inintstall) {
				// TODO Auto-generated method stub
			}
			
			@Override
			public void processResponse(String response) {
				if (response != null && response != "" ) {
					try {
						Log.d("Q_Album", "getalbumdetail: "+ response);
						JSONObject jsonObject = new JSONObject(response);
						if (jsonObject != null) {
							int code = ParseJSON.getIntValue(jsonObject, Constants.PARAM_RESPONSE_CODE);
							if (code != 1) { // khong du dieu kien xem noi dung
								// Yeu cau Thanh toan
								PaymentControl paymentControl = new PaymentControl(mainActivity);
								paymentControl.startPayment(new ResponseListener() {
									
									@Override
									public void processResponse(int inintstall) {
										// TODO Auto-generated method stub
										
									}
									
									@Override
									public void processResponse(String response) {
										// TODO Auto-generated method stub
										
									}
								});
								return;
							}
						}
					} catch (JSONException e) {
						e.printStackTrace();
						return;
					}
				}
				
				AlbumEntity albumEntity = ParseJSON.getAlbumObjectFromResponse(response);
				setWidgetInfo(albumEntity);
			}
		});
	}
	
	protected void setWidgetInfo(AlbumEntity albumEntity) {
		//QuangLM_20140507 fix bug #236
		//start
		albumEntity.setTotalView(album_view);
		//end
		txvModelName.setText(albumEntity.getModelName());
		txvAlbumTitle.setText(albumEntity.getName());
		txvAlbumUpdateTime.setText(String.format(getString(R.string.text_created_at), albumEntity.getCreated()));
		
		String totalView = albumEntity.getTotalView() + " views";
		txvTotalView.setText(totalView);
		txvIntroduction.setText(albumEntity.getCaption());
		
		if (albumEntity.getModelIcon() == null || albumEntity.getModelIcon().trim().isEmpty()) {
			imvModelImage.setVisibility(View.GONE);
		} else {
			imvModelImage.setVisibility(View.VISIBLE);
			
			int icon_size = ConfigUtility.size_icon;
			LinearLayout.LayoutParams param1 = new LinearLayout.LayoutParams(icon_size, icon_size);
			imvModelImage.setLayoutParams(param1);
			imvModelImage.setScaleType(ScaleType.FIT_CENTER);

			//QuangLM_20140507 fix bug #217
			//start  
//			mainActivity.loadImage(imvModelImage, imageUrl, icon_size, icon_size, icon_size, icon_size);
			mainActivity.loadImage(imvModelImage, albumEntity.getModelIcon(), icon_size, icon_size, icon_size, icon_size);
			//end
		}
		
		// list tags
		ArrayList<TagEntity> listTags = albumEntity.getTags();
		if (listTags != null)
			for (int i = 0; i < listTags.size(); i++) {
				String tag = listTags.get(i).getName();
				TextView textView = new TextView(mainActivity);
				textView.setPadding(5, 5, 5, 5);
				textView.setTextColor(Color.BLUE);
				textView.setOnClickListener(new TagOnClickListener(tag));
				if (i != listTags.size()-1) 
					tag += ",";
				textView.setText(tag);
				layoutTags.addView(textView);
			}
		
		// gallery Image
		ArrayList<GalleryEntity> listGallery = albumEntity.getGalleries();
		AlbumDetailFragment.this.listGallery = listGallery;
		if (listGallery != null && listGallery.size() > 0) {
			imgMainItem.setVisibility(View.VISIBLE);
			layoutListItem.setVisibility(View.VISIBLE);
			
			widthImage = ConfigUtility.size_full_width;
			heightImage = (int) (widthImage * ConfigUtility.scale_size_horizontal_thumbs_item);
			
			widthImageView = ConfigUtility.scrWidth;
			heightImageView = (int) (widthImageView * ConfigUtility.scale_size_horizontal_thumbs_item);
			
			RelativeLayout.LayoutParams param2 = new RelativeLayout.LayoutParams(widthImageView, heightImageView);
			imgMainItem.setLayoutParams(param2);
			imgMainItem.setScaleType(ScaleType.FIT_CENTER);
			
			imageUrl = listGallery.get(0).getThumb();
			imgMainItem.setOnClickListener(new AlbumItemOnClickListener(true));
			
			mainActivity.loadImage(imgMainItem, imageUrl, widthImage, heightImage, widthImageView, heightImageView);
			
			int widthImage3 = ConfigUtility.size_half_width;
			int heightImage3 = (int) (widthImage3 * ConfigUtility.scale_size_horizontal_thumbs_item);
			
			int widthImageView3 = ConfigUtility.scrWidth * 2 / 7;
			int heightImageView3 = (int) (widthImageView3 * ConfigUtility.scale_size_horizontal_thumbs_item);
			
			LinearLayout.LayoutParams param3 = new LinearLayout.LayoutParams(widthImageView3, heightImageView3);
			param3.leftMargin = 6;
			
			for (int i = 0; i < listGallery.size(); i++) {
				ImageView imageView = new ImageView(mainActivity);
				if (i == 1) 
					param3.leftMargin = 0;
				else
					param3.leftMargin = 6;
				
				imageView.setLayoutParams(param3);
				imageView.setScaleType(ScaleType.FIT_CENTER);
//				Log.d("image thumb", "link:" + listGallery.get(i).getThumb80x80());
				mainActivity.loadImage(imageView, listGallery.get(i).getThumb80x80(), widthImage3, heightImage3, widthImageView3, heightImageView3);
				
				layoutListItem.addView(imageView);
				imageView.setTag(i);
				imageView.setOnClickListener(new AlbumItemOnClickListener(listGallery.get(i).getThumb(), false));
			}
		} else {
			imgMainItem.setVisibility(View.GONE);
			layoutListItem.setVisibility(View.GONE);
		}
	}
	
	private void requestSuggestionData() {
		if (isRequestSuggestionData)
			return;
		
		isRequestSuggestionData = true;
		// Lay list Album lien quan
		amazingListViewAlbumSuggestion.setAdapter(albumAdapter = new AlbumSuggestionAdapter(this, Constants.CATEGORY_ALBUM_DETAIL, album_id));
		amazingListViewAlbumSuggestion.setLoadingView(getActivity().getLayoutInflater().inflate(R.layout.layout_loading_view, null));
		
		albumAdapter.setAmazingListView(amazingListViewAlbumSuggestion, ConfigUtility.PAGE_SIZE);
		albumAdapter.notifyMayHaveMorePages();
		
		// Chuyen toi detail
		amazingListViewAlbumSuggestion.setOnItemClickListener(new OnItemClickListener() {
			public void onItemClick(AdapterView<?> arg0, View arg1, int position, long arg3) {
				if (albumAdapter != null && position >= 0) {
					albumAdapter.onItemClick(position);
				}
			}
		});
					
		albumAdapter.resetList();
	}
	
	private void requestCommentData() {
		if (isRequestCommentData)
			return;
		
		isRequestCommentData = true;
		// Lay list comment cua Album
		amazingListViewAlbumComments.setAdapter(commentAdapter = new CommentAdapter(this, Constants.CATEGORY_ALBUM_DETAIL, Constants.COMMENT_TYPE_ALBUM, album_id));
		amazingListViewAlbumComments.setLoadingView(getActivity().getLayoutInflater().inflate(R.layout.layout_loading_view, null));
		
		commentAdapter.setAmazingListView(amazingListViewAlbumComments, ConfigUtility.PAGE_SIZE);
		commentAdapter.notifyMayHaveMorePages();
		
		commentAdapter.resetList();
	}
	
	public void postComment() {
		String comment = edtComment.getText().toString();
		if (comment != null && comment.length() > 0) {
			mainActivity.postComment(Constants.COMMENT_TYPE_ALBUM, album_id, comment, new ResponseListener() {
				
				@Override
				public void processResponse(int inintstall) {
					// TODO Auto-generated method stub
					
				}
				
				@Override
				public void processResponse(String response) {
					 boolean resultPostComment = ParseJSON.getResultPostCommentFromResponse(response);
					 if (resultPostComment) {
						 edtComment.setText("");
						 isRequestCommentData = false;
						 requestCommentData();
					 }
				}
			});
		} else {
			DialogUtility.showDialogAlert(mainActivity, null, getString(R.string.text_empty_comment), getString(R.string.label_close),
				new DialogListener() {
					public void after() {
						showKeyBoard(edtComment);
					}
				});
		}
		InputMethodManager imm = (InputMethodManager)getActivity().getSystemService(
			      Context.INPUT_METHOD_SERVICE);
		imm.hideSoftInputFromWindow(edtComment.getWindowToken(), 0);
	}
	private ArrayList<GalleryEntity> listGallery;
	private int index = 0;
	private class AlbumItemOnClickListener implements OnClickListener {

		private String imageUrl;
		private boolean isMainImage;
		
		public AlbumItemOnClickListener(boolean isMainImage) {
			this.isMainImage = isMainImage;
		}
		
		public AlbumItemOnClickListener(String imageUrl, boolean isMainImage) {
			this.imageUrl = imageUrl;
			this.isMainImage = isMainImage;
		}
		
		@Override
		public void onClick(View v) {
			if (isMainImage) {
				Intent intent = new Intent(mainActivity, ImageViewerActivity.class);
				String[] arr = new String [listGallery.size()];
				for(int i= 0;i<arr.length;i++){
					arr[i]= listGallery.get(i).getThumb();
				}
				intent.putExtra("imageUrl", arr);
				intent.putExtra("index", index);
				startActivity(intent);
			} else {
				mainActivity.loadImage(imgMainItem, this.imageUrl, widthImage, heightImage, widthImageView, heightImageView);
				AlbumDetailFragment.this.imageUrl = this.imageUrl;
				AlbumDetailFragment.this.index = (Integer) v.getTag();
			}
		}
	}
	
	private class TagOnClickListener implements OnClickListener {

		private String tag;
		public TagOnClickListener(String tag) {
			this.tag = tag;
		}
		
		@Override
		public void onClick(View v) {
			mainActivity.openSearchFragmen(tag, Constants.TAB_VIEW_SEARCH_ALBUM, true);
		}
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.layoutButtonIntroduction:
			switchTab(Constants.TAB_MODE_ALBUM_INTRODUCTION);
			break;
		case R.id.layoutButtonSuggestion:
			switchTab(Constants.TAB_MODE_ALBUM_SUGGESTION);
			break;
		case R.id.layoutButtonComment:
			switchTab(Constants.TAB_MODE_ALBUM_COMMENT);
			break;
		case R.id.buttonComment:
			postComment();
			break;
		}
	}
	
	public static AlbumDetailFragment newInstance(String id) {
		AlbumDetailFragment myFragment = new AlbumDetailFragment();
		myFragment.album_id = id;
		
		return myFragment;
	}
	public static AlbumDetailFragment newInstance(String id, String numViews) {
		AlbumDetailFragment myFragment = new AlbumDetailFragment();
		myFragment.album_id = id;
		myFragment.album_view = numViews;
		return myFragment;
	}
	
	public void refresh() {
		if (commentAdapter != null) {
			commentAdapter.clear();
		}
		
		if (albumAdapter != null) {
			albumAdapter.clear();
		}
	
		setBaseValues();
		
		resetAllView();
		
		switchTab(Constants.TAB_MODE_ALBUM_INTRODUCTION);
	}
	
	public void resetAllView() {
		if (txvModelName != null) txvModelName.setText("");
		if (txvAlbumTitle != null) txvAlbumTitle.setText("");
		if (txvAlbumUpdateTime != null) txvAlbumUpdateTime.setText("");
		if (txvTotalView != null) txvTotalView.setText("");
		if (txvIntroduction != null) txvIntroduction.setText("");
		if (layoutTags != null) layoutTags.removeAllViews();
		if (layoutListItem != null) layoutListItem.removeAllViews();
	}
	 
	public void showKeyBoard(EditText editText) {
		if (editText != null) {
			editText.setFocusable(true);
			editText.setFocusableInTouchMode(true);
			editText.requestFocus();
			InputMethodManager inputMethodManager = ((InputMethodManager) mainActivity.getSystemService(Context.INPUT_METHOD_SERVICE));
			inputMethodManager.showSoftInput(editText, 1);
		}
	}

	public void hideKeyBoard(EditText editText) {
		if (editText != null) {
			((InputMethodManager) mainActivity.getSystemService(Context.INPUT_METHOD_SERVICE)).hideSoftInputFromWindow(editText.getWindowToken(), 0);
		}
	}

}
